package cn.com.inossem.base;

import java.util.ArrayList;

import android.app.Service;
import android.os.Bundle;
import cn.com.inossem.requestmanager.WooRequestManager;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;

/**
 * 
 * The goal of this base class: 
 * 1. bind the Datadroid to use 
 * 2. bind the lifecycle of service to Datadroid callback
 * 
 */
public abstract class RequestService extends Service implements RequestBase {
	protected WooRequestManager mRequestManager = null;
	protected ArrayList<Request> mRequestList = null;
	protected boolean mContextDestroyed = false;

	@Override
	public void onCreate() {
		super.onCreate();
		initAllMembers(null);
	}

	@Override
	public void onDestroy() {
		mContextDestroyed = true;
		super.onDestroy();
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		mContextDestroyed = false;
		mRequestManager = WooRequestManager.from(this);
		mRequestList = new ArrayList<Request>();
	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {

	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	@Override
	public final void launchRequest(Request request) {
		if (request != null) {
			if (Utils.isNetworkAvailable(this)) {
				mRequestManager.execute(request, this);
				mRequestList.add(request);
			} else {
				handleException(EXCEPTION_TYPE_NETWORK);
			}
		}
	}

	@Override
	public final void onRequestConnectionError(Request arg0, int arg1) {
		if (mRequestList.contains(arg0)) {
			mRequestList.remove(arg0);
		}

		if (arg1 == -1) {
			handleException(EXCEPTION_TYPE_NETWORK);
		} else {
			handleException(EXCEPTION_TYPE_SERVER_NO_RESPONSE);
		}
	}

	@Override
	public final void onRequestCustomError(Request arg0, Bundle arg1) {
		if (mRequestList.contains(arg0)) {
			mRequestList.remove(arg0);
		}

		handleException(EXCEPTION_TYPE_CUSTOM_BASE);
	}

	@Override
	public final void onRequestDataError(Request arg0) {
		if (mRequestList.contains(arg0)) {
			mRequestList.remove(arg0);
		}

		handleException(EXCEPTION_TYPE_DATA);
	}

	@Override
	public final void onRequestFinished(Request arg0, Bundle arg1) {
		if (mContextDestroyed) {
			return;
		}

		if (mRequestList.contains(arg0)) {
			onRequestSucess(arg0, arg1);
			mRequestList.remove(arg0);
		}
	}

	@Override
	public final void handleException(int exceptionType) {
		if (mContextDestroyed) {
			return;
		}
		onRequestError(exceptionType);
	}
}
